from db_base import DatabaseManager, dbconfig

class PlanManager:
    def __init__(self):
        self.db_manager = DatabaseManager(dbconfig)

    def __del__(self):
        self.db_manager.close()

    def get_patient_list(self):
        """获取治疗师负责的患者列表"""
        query = """
        SELECT user_id as id, username as name 
        FROM users 
        WHERE role = 'patient'
        """
        try:
            result = self.db_manager.execute_query(query,())
            return result
        except Exception as e:
            print(f"获取患者列表失败: {e}")
            return []

    def get_plan_exercises(self, plan_id):
        """获取计划的所有训练项目"""
        query = """
        SELECT exercise_id, exercise_type, duration_minutes,
               repetitions, resistance_level, instructions
        FROM training_exercises
        WHERE plan_id = %s
        ORDER BY created_at
        """
        try:
            return self.db_manager.execute_query(query, (plan_id,))
        except Exception as e:
            print(f"获取训练项目失败: {e}")
            return None

    def get_therapist_plans(self, therapist_id):
        """获取治疗师负责的所有康复计划"""
        query = """
        SELECT p.plan_id, p.plan_name, p.start_date, p.end_date,
               p.status, u.username AS patient_name
        FROM rehabilitation_plans p
        JOIN users u ON p.patient_id = u.user_id
        WHERE p.therapist_id = %s
        ORDER BY p.start_date DESC
        """
        try:
            return self.db_manager.execute_query(query, (therapist_id,))
        except Exception as e:
            print(f"获取治疗师计划失败: {e}")
            return None

    def create_rehab_plan(self, plan_data):
        """数据库层面创建康复计划"""
        query = """
        INSERT INTO rehabilitation_plans (
            patient_id, therapist_id, plan_name, 
            start_date, end_date, frequency, status
        ) VALUES (%s, %s, %s, %s, %s, %s, %s)
        """
        values = (
            plan_data['patient_id'],
            plan_data['therapist_id'],
            plan_data['plan_name'],
            plan_data['start_date'],
            plan_data['end_date'],
            plan_data['frequency'],
            plan_data['status']
        )
        try:
            self.db_manager.execute_query(query, values, commit=True)
            return self.db_manager.cursor.lastrowid
        except Exception as e:
            raise Exception(f"数据库创建失败: {str(e)}")

    def update_plan(self, plan_data):
        """数据库层面更新康复计划"""
        query = """
        UPDATE rehabilitation_plans 
        SET plan_name=%s, start_date=%s, end_date=%s,
            frequency=%s, status=%s
        WHERE plan_id=%s
        """
        values = (
            plan_data['plan_name'],
            plan_data['start_date'],
            plan_data['end_date'],
            plan_data['frequency'],
            plan_data['status'],
            plan_data['plan_id']
        )
        try:
            self.db_manager.execute_query(query, values, commit=True)
            return True
        except Exception as e:
            raise Exception(f"数据库更新失败: {str(e)}")

    def delete_rehab_plan(self, plan_id):
        """删除康复计划（级联删除关联的训练项目）"""
        try:
            # 先删除关联的训练项目
            self.db_manager.execute_query(
                "DELETE FROM training_exercises WHERE plan_id = %s",
                (plan_id,), commit=True
            )
            # 再删除计划
            self.db_manager.execute_query(
                "DELETE FROM rehabilitation_plans WHERE plan_id = %s",
                (plan_id,), commit=True
            )
            return True
        except Exception as e:
            print(f"删除计划失败: {e}")
            return False


    def get_plan_details(self, plan_id):
        """获取康复计划完整详情"""
        query = """
        SELECT p.*, 
               pt.username AS therapist_name,
               pat.username AS patient_name
        FROM rehabilitation_plans p
        JOIN users pt ON p.therapist_id = pt.user_id
        JOIN users pat ON p.patient_id = pat.user_id
        WHERE p.plan_id = %s
        """
        try:
            result = self.db_manager.execute_query(query, (plan_id,))
            return result[0] if result else None
        except Exception as e:
            print(f"获取计划详情失败: {e}")
            return None

    def add_plan_exercise(self, plan_id, exercise_data):
        """为康复计划添加训练项目"""
        query = """
        INSERT INTO training_exercises (
            plan_id, exercise_type, duration_minutes,
            repetitions, resistance_level, instructions
        ) VALUES (%s, %s, %s, %s, %s, %s)
        """
        values = (
            plan_id,
            exercise_data['exercise_type'],
            exercise_data['duration_minutes'],
            exercise_data['repetitions'],
            exercise_data.get('resistance_level'),
            exercise_data.get('instructions', '')
        )
        try:
            self.db_manager.execute_query(query, values, commit=True)
            return self.db_manager.cursor.lastrowid
        except Exception as e:
            print(f"添加训练项目失败: {e}")
            return None